<?php

/**
 * This is the model class for table "user".
 *
 * The followings are the available columns in table 'user':
 * @property string $id
 * @property string $username
 * @property string $password
 * @property string $display_name
 * @property integer $money
 * @property integer $experience
 * @property integer $level
 * @property integer $type
 * @property string $phone
 * @property string $email
 * @property string $avatar
 */
class User extends CActiveRecord
{
  //to put the value that user type in for check the password they typed before, only working on three sceniros Create, Change Pass, and Admin Update  
  public $password_repeat; 
  
  //hold the old password user input, when change password
  public $password_old;
  
	/**
	 * Returns the static model of the specified AR class.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{user}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('username, password, display_name,', 'required'),
			array('password_old', 'required', 'on'=>'updatePass'),
		  array('password','compare', 'on'=>'create, updatePass'),
		  
		  
			array('username, password,password_old', 'length', 'min'=>3 ,'max'=>32, 'encoding'=>'utf-8'),
			array('display_name', 'length', 'min'=>6, 'max'=>24, 'encoding'=>'utf-8'),
			array('phone', 'length', 'max'=>16),
			array('email', 'length', 'max'=>64),
			
			array('avatar', 'file', 'allowEmpty'=>true, 'maxSize'=>1*1024*1024, 'types'=>'jpg'),
			
			array(' money, experience, level, type, phone, email, avatar, password_repeat', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, username, password, display_name, money, experience, level, type, phone, email, avatar', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'username' => 'Username',
			'password' => 'Password',
			'password_repeat' => 'Password Repeat',
			'password_old' => 'Old Password',
			'display_name' => 'Display Name',
			'money' => 'Money',
			'experience' => 'Experience',
			'level' => 'Level',
			'type' => 'Type',
			'phone' => 'Phone',
			'email' => 'Email',
			'avatar' => 'Avatar',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('display_name',$this->display_name,true);
		$criteria->compare('money',$this->money);
		$criteria->compare('experience',$this->experience);
		$criteria->compare('level',$this->level);
		$criteria->compare('type',$this->type);
		$criteria->compare('phone',$this->phone,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('avatar', $this->avatar, true );
        
        return new CActiveDataProvider ( get_class ( $this ), array ('criteria' => $criteria ) );
    }
    
    public function beforeSave() {
        if (parent::beforeSave ()) {
            if ($this->isNewRecord) {
                $this->level = $this->experience = 0;
                $this->money = 100;
                $this->password = $this->encrypt($this->password);
            }
            
//            if (isset($this->password_old)){
//                $this->password = $this->encrypt($this->password);
//            }
            
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 
     * rand string for filename like this.
     * @param unknown_type $len
     * @param unknown_type $format
     */
    function randStr($len = 6, $format = 'ALL_WORD') {
        switch ($format) {
            case 'ALL_WORD' :
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                break;
            case 'ALL' :
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
                break;
            case 'CHAR' :
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~'; break;
            case 'NUMBER' :
                $chars = '0123456789';
                break;
            default :
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
                break;
        }

        mt_srand ( ( double ) microtime () * 1000000 * getmypid () );
        $password = "";
        
        while ( strlen ( $password ) < $len )
            $password .= substr ( $chars, (mt_rand () % strlen ( $chars )), 1 );
        return $password;
     }
    
    /**
     * check the password input is the same with the value store in database
     * @param string $password
     * @return boolean true/false
     */
    public function validatePassword($password) {
        return $this->password === $this->encrypt ( $password );
    }
    
    /**
     * use one php build-in method to encrypt a string, this way we are use method md5()
     * @param string $password
     * @return string after encrypt
     */
    public function encrypt($password) {
        return md5($password);
    }
    
    /**
     * 
     * return user's money.
     */
    public function getUserMonty()
    {
        $current = User::model()->findByPk(Yii::app()->user->id);
        return $current->money;
    }
    
    /**
     * 
     * get all children belong to this account from db
     * 
     * @return an array for dropDownList date.
     */
    public function getAllChildren()
    {
        $pSRelations = PsRelation::model()->findAllByAttributes(array('uid'=>Yii::app()->user->id));
        $returnArr = array();

        foreach ($pSRelations as $relation){
             $childInfo = $relation->childInfo;
             $returnArr[$childInfo->id] = $childInfo->display_name ;   
        }
        return $returnArr;
    }
}